//
//  GoodListViewController.m
//  yigou
//
//  Created by wangdianlei on 2017/2/17.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "GoodListViewController.h"
#import "MarketGoodsCell.h"
#import "GoodDetailViewController.h"
#import "MMMarketType.h"

static const NSInteger kButtonTag = 8800;

@interface GoodListViewController () <UITableViewDelegate, UITableViewDataSource, MarketGoodCellDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *topbar;

@property (strong, nonatomic) NSMutableArray *searchResult;
@property (strong, nonatomic) NSMutableArray *typeArray;
@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) BOOL pageToEnd;

@end

@implementation GoodListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"我的作品"];
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIView *blankView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
    self.tableView.tableFooterView = blankView;
    [self addLoadMoreFooter:self.tableView];
    
    self.pageToEnd = NO;
    self.page = 1;
    
    [self loadNetworkData];
    [self loadTypeData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)goPop {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
}

- (void)makeTopBar {
    NSInteger count = self.typeArray.count;
    
    for (NSInteger i= 0; i < count; i++) {
        MMMarketType *one = self.typeArray[i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = kButtonTag + i;
        button.frame = CGRectMake(ScreenWidth / count * i, 0, ScreenWidth / count, 50);
        [button setTitle:one.type_name forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [self.topbar addSubview:button];
        
        [button addTarget:self action:@selector(clickType:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)loadNetworkData {
    self.page = 1;
    self.pageToEnd = NO;
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/product/selectMyProduct?page=%ld", APIYIGOU, self.page];
    request.requestUrl =  [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        self.page += 1;
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        [JSONModel addDatasFromDict:[dict objectForKey:@"data"] withModel:@"MMMarketNew" forKey:@"list" target:self.searchResult isAppend:NO];
        [ViewFactory dismissLoading];
        [self.tableView reloadData];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showInfoMsg:@"查询失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

- (void)loadMore {
    if (self.pageToEnd) {
        [ViewFactory showInfoMsg:@"没有下一页了！"];
        [self.tableView.footer endRefreshing];
        return;
    }
    
    //    if (!self.marketTypeName) {
    //        self.marketTypeName = @"";
    //    }
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/product/selectMyProduct?page=%ld", APIYIGOU, self.page];
    request.requestUrl =  [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        self.page += 1;
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSArray *array = [[dict objectForKey:@"data"] objectForKey:@"list"];
        if (array.count == 0) {
            self.pageToEnd = YES;
        }
        [JSONModel addDatasFromDict:[dict objectForKey:@"data"] withModel:@"MMMarketNew" forKey:@"list" target:self.searchResult isAppend:YES];
        [ViewFactory dismissLoading];
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (self.searchResult.count / 2 + self.searchResult.count % 2);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 307 - 50 - 15;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MarketGoodsCell *cell = GET_CELL(MarketGoodsCell, @"MarketGoodsCell");
    cell.titleH.constant = 0;
    cell.lineH.constant = 0;
    cell.title.hidden = YES;
    cell.line.hidden = YES;
    
    MMMarketNew *ldata = nil;
    MMMarketNew *rdata = nil;
    if (self.searchResult.count > indexPath.row * 2) {
        ldata = [self.searchResult objectAtIndex:(indexPath.row * 2)];
    }
    if (self.searchResult.count > indexPath.row * 2 + 1) {
        rdata = [self.searchResult objectAtIndex:(indexPath.row * 2 + 1)];
    }
    
    cell.type = IMarketGoodCellNew;
    cell.index = indexPath.row;
    cell.delegate = self;
    [cell fillWithData:ldata right:rdata];
    return cell;
}

- (void)clickMarketGoodCell:(NSInteger)index isLeft:(BOOL)clickLeft myType:(MarketGoodCellType)type {
    MMMarketNew *gooddata = nil;
    if (clickLeft) {
        gooddata = [self.searchResult objectAtIndex:index * 2];
    } else {
        gooddata = [self.searchResult objectAtIndex:(index * 2 + 1)];
    }
    
    if (gooddata) {
        [[GoToManager sharedGoToManager] go:self type:ToGoodDetail data:gooddata];
    }
}

- (void)loadTypeData {
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/product/showProductType", APIYIGOU];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        [JSONModel addDatasFromDict:dict withModel:@"MMMarketType" forKey:@"data" target:self.typeArray isAppend:NO];
        [self makeTopBar];
    } error:^(YTKBaseRequest *request) {
    } failure:^(YTKBaseRequest *request) {
    }];
}

- (void)clickType:(UIButton *)sender {
    NSInteger tag = sender.tag - kButtonTag;
    [sender setTitleColor:QINGColor forState:UIControlStateNormal];
    
    for (NSInteger i = 0; i < self.typeArray.count; i++) {
        if (i != tag) {
            UIButton *button = (UIButton *)[self.topbar viewWithTag:i + kButtonTag];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }
    
    MMMarketType *one = self.typeArray[tag];
    self.page = 1;
    self.pageToEnd = NO;
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/product/selectMyProduct?page=%ld&goods_kind=%@", APIYIGOU, self.page, one.theid];
    request.requestUrl =  [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        self.page += 1;
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        [JSONModel addDatasFromDict:[dict objectForKey:@"data"] withModel:@"MMMarketNew" forKey:@"list" target:self.searchResult isAppend:NO];
        [ViewFactory dismissLoading];
        [self.tableView reloadData];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showInfoMsg:@"查询失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

ARRAY_INIT(typeArray)
ARRAY_INIT(searchResult)

@end
